<?php
    class LikesController extends AppController{
        public $name = 'Likes';

        public function  beforeFilter() {
            parent::beforeFilter();
            $this->setLayout();
            $this->Auth->allow('*');
        }
        public function addLike($objectId, $objectType){
            $userId = $this->Bayon->userId();
            
            if( $userId ){
                    $data = array(
                            'Like' =>array(
                                'user_id' => $userId,
                                'object_id' => $objectId,
                                'object_type' => $objectType
                            )
                        );
                    $this->Like->create();
                    if($this->Like->save($data)){

                        //initial to redirect
                        if($objectType == OBJECT_TYPE_COMPANY){
                            $this->loadModel('Company');
                            $this->Company->recursive = -1;
                            $slug = $this->Company->read('slug', $objectId);
                            $this->redirect($slug['Company']['slug']);

                         }else{
                            $this->cakeError('error404');
                         }
                        //$this->set('result', array('error' => 0, 'message' => 'Insert success'));
                    }else{
                        
                    }
            }else{
                $this->Session->setFlash(__('Access deny! you must to login', true));
                $this->set('result', array('error' => -1, 'message' => 'You need to login'));
                
            }
        }


        public function unlike($objectId, $objectType){
            if($objectId){
                $userId = $this->Bayon->userId();
                $like = $this->Like->find('first', array('conditions' => array('Like.user_id' => $userId, 'Like.object_id' => $objectId, 'Like.object_type' => $objectType), 'recursive' => -1));
                //delete
                $this->Like->delete($like['Like']['id']);
                //initial to redirect
                if($objectType == OBJECT_TYPE_COMPANY){
                     $this->loadModel('Company');
                     $this->Company->recursive = -1;
                     $slug = $this->Company->read('slug', $objectId);
                     $this->redirect($slug['Company']['slug']);

                }else{
                   $this->redirect('/');
               }
            }else{
                $this->cakeError('error404');
            }
        }
}
?>
